<?php namespace App\Application;

use App\Exceptions\Item\OrderException;
use App\Repositories\Order\OrderRepositoryInterface;

class OrderService
{
    /**
     * @var OrderRepositoryInterface
     */
    protected $order_repository;

    public function __construct()
    {
        $this->order_repository = app(OrderRepositoryInterface::class);
    }

    public function show($id, $user_id)
    {
        $order = $this->order_repository->showWithThrow($id);
        if ($order->user_id != $user_id) {
            throw new OrderException(OrderException::NOT_FOUND);
        }

        if (!$order->isPaidSuccess()) {
            throw new OrderException(OrderException::NOT_FOUND);
        }

        $order->load('user', 'publisher', 'appeal', 'message');
        $this->loadOrderItem($order);

        return $order->toArray();
    }

    public function userOrders($user_id, $per_page)
    {
        $orders = $this->order_repository->userOrders($user_id, $per_page);
        $orders->load('publisher');
        $this->loadOrderItem($orders);
        $pager = $orders->toArray();
        $data = array_pull($pager, 'data');

        return compact('data', 'pager');
    }

    public function showPublisherOrder($id, $publisher_uid)
    {
        $order = $this->order_repository->showWithThrow($id);
        if ($order->publisher_uid != $publisher_uid) {
            throw new OrderException(OrderException::NOT_FOUND);
        }

        if (!$order->isPaidSuccess()) {
            throw new OrderException(OrderException::NOT_FOUND);
        }

        $order->load('user', 'publisher', 'appeal', 'message');
        $this->loadOrderItem($order);

        return $order->toArray();
    }

    public function publisherOrders($publisher_uid, $per_page)
    {
        $orders = $this->order_repository->publisherOrders($publisher_uid, $per_page);

        $orders->load('user');
        $this->loadOrderItem($orders);
        $pager = $orders->toArray();
        $data = array_pull($pager, 'data');

        return compact('data', 'pager');
    }

    private function loadOrderItem($order)
    {
        $order->load('item.contact', 'item.stage', 'item.project', 'item.publisher', 'item.company', 'item.tags');
    }

}
